<script setup>
import {ElementUtils} from "@/assets/js/ElementUtils";
import {ThreadUtils} from "@/assets/js/ThreadUtils";
import {setWindowTitle} from "@/assets/js/TitleUtils";
import {setupMapActions, setupMapGetters, setupMapState} from "@/assets/js/vuexUtils";
import FavorFolderList from "@/components/thread/FavorFolderList.vue";
import ForumOperations from "@/components/thread/ForumOperations.vue";
import TopicTable from "@/components/thread/TopicTable.vue";
import {routeNames} from "@/router";
import {NukeApi} from "@ginstone/nga-api/dist/src/method/NukeApi";
import {FavorDelParam} from "@ginstone/nga-api/dist/src/params/NukeParams";
import {ElMessageBox} from "element-plus";
import {h, onMounted, onUnmounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import PrivilegeDialog from "@/components/common/dialog/PrivilegeDialog.vue";
import SubForumDialog from "@/components/common/dialog/SubForumDialog.vue";
import ToppedTopicDialog from "@/components/common/dialog/ToppedTopicDialog.vue";
import BlockedTopicsDialog from "@/components/common/dialog/BlockedTopicsDialog.vue";
import {DomUtils} from "@/assets/js/DomUtils";
import {KeyPressListener} from "@ginstone/common-utils/dist/src/utils/KeyPressListener";
import HotkeyDialog from "@/components/common/dialog/HotkeyDialog.vue";

const {currentFavorForum} = setupMapState("Account", ["currentFavorForum"])
const getClient = setupMapGetters("Account", ["getClient"]).getClient.value
const {thread} = setupMapActions("Thread", ['thread'])

const route = useRoute()
const router = useRouter()

// 匹配的路由名称
const threadRouteName = routeNames.thread
// 分页数据
const pageData = ref();
// 主题列表
const topics = ref();
// 版面标题
const title = ref();
// 版面信息
const forum = ref();
// 总数据
const data = ref();
// 应用返回数据
// 显示跳转按钮的路由
const jumpRoute = [threadRouteName.forumList, threadRouteName.forumSearch, threadRouteName.colList, threadRouteName.colSearch, threadRouteName.recommend]
// 被选中的主题
const selection = ref();
// loading动画
let loading;

setWindowTitle("主题列表")

const applyResult = (res) => {
  data.value = res;
  // 主题列表
  topics.value = res.topics
  forum.value = res.forum
  // 版面标题
  if (res.forum) {
    title.value = res.forum.colTitle || res.forum.forumName + (route.name === threadRouteName.recommend ? " (精华区)" : "")
  } else if (route.name === routeNames.user.topic) {
    title.value = "用户发布的主题"
  } else if (route.name === routeNames.user.replies) {
    title.value = "用户发布的回复"
  } else if (route.name === routeNames.thread.favor) {
    title.value = "用户收藏"
  }

  setWindowTitle(title.value + " - 主题列表")

  // 分页数据
  if (res.total && res.size) {
    const totalPage = Math.floor(res.total / res.size) + (res.total % res.size === 0 ? 0 : 1)
    pageData.value = {size: res.size, total: res.total, totalPage}
  } else if (res.size) {
//    如果没有提供分页信息，尝试自动识别
    const totalPage = Number(route.query.page || 1) + 5
    const total = totalPage * res.size;
    pageData.value = {size: res.size, total, totalPage}
  }

}
const refresh = () => {
  request(route, true)
}

/**
 * 执行请求
 * @param route 当前路由
 * @param force 强制请求绕过缓存
 */
const request = (route, force) => {
  const params = ThreadUtils.buildParamsFromRoute(route);
  if (!params) {
    return
  }
  // loading为undefined时才创建新的loading动画
  !loading && (loading = ElementUtils.loading({target: "#content",}));

  // 如果访问默认收藏夹, 先不发送请求
  if (route.name === routeNames.thread.favor && route.params.id === "1") {
    applyResult([]);
    return;
  }
  thread({params, force}).then(res => {
    applyResult(res);
    console.log(res)
  }).catch(reason => {
    ElementUtils.exceptionHandler(reason)
    router.back();

  }).finally(() => {
    loading.close();
    loading = undefined;
  })
}
// 被选中的主题变化
const selectionChanged = (e) => {
  selection.value = e
}
// 移除收藏
const favorTopicDel = () => {
  const arr = selection.value
  if (!arr || arr.length === 0) {
    return
  }
  ElMessageBox({
    title: "移除收藏",
    type: "warning",
    message: h('div', null, [
      h('h3', '即将移除以下收藏:'),
      ...arr.map(i => h('div', null, i.title))
    ]),
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showCancelButton: true,
    showConfirmButton: true,
  }).then(res => {
    if (res === 'confirm') {
      const p = arr.map(({topicId, reply}) => {
        const tid = topicId
        const pid = reply ? reply.replyId : undefined
        return {tid, pid}
      })
      // 移除请求
      NukeApi.favorTopicDel(getClient(), new FavorDelParam(route.params.page || 1, p)).then(res => {
        ElementUtils.notice({message: res})
        request(route);
      })
    }
  })
}


// 快捷键触发条件
const condition = (e) => {
  // console.log(e)
  const {target} = e
  // 输入框不触发
  return !target.hasOwnProperty("cmView") && target.nodeName !== 'INPUT' && target.localName !== 'input'
}

/**
 * 跳转到指定页
 * @param page
 */
const goPage = (page) => {
  if (pageData.value && pageData.value.totalPage) {
    DomUtils.scrollTop();
    page = Math.max(1, page);
    page = Math.min(pageData.value.totalPage, page);
    const query = {...route.query, page}
    router.push({query});
  }
}

const pageActions = [
  {
    name: "前一页",
    event: {code: "KeyA", condition}, method: () => {
      const page = route.query.page ? Number(route.query.page) : 1;
      goPage(page - 1)
    },
  }, {
    name: "后一页",
    event: {code: "KeyD", condition}, method: () => {
      const page = route.query.page ? Number(route.query.page) : 1;
      goPage(page + 1)
    },
  }, {
    name: "第一页",
    event: {code: "KeyA", shiftKey: true, condition}, method: () => {
      goPage(1)
    },
  }, {
    name: "最后一页",
    event: {code: "KeyD", shiftKey: true, condition}, method: () => {
      goPage(Number.MAX_VALUE)
    },
  }, {
    name: "刷新",
    event: {code: "KeyR", altKey: true, condition}, method: () => {
      refresh()
    },
  },
]

const pageKeyListener = new KeyPressListener(pageActions, undefined, false);
const triggerType = "keydown"


onMounted(() => {
  request(route);
  window.addEventListener(triggerType, pageKeyListener.listener, false)
})

onUnmounted(() => {
  window.removeEventListener(triggerType, pageKeyListener.listener)
})

watch(route, (nv) => {
  request(nv)
})

</script>

<template>
  <div style="text-align: left">
    <!--收藏夹相关-->
    <div v-if="$route.name=== routeNames.thread.favor">
      <el-link :href="ThreadUtils.buildOfficialUrlFromRoute($route)" target="_blank">
        <h3>用户的收藏</h3>
      </el-link>
      <favor-folder-list/>
      <div>
        <el-button type="danger" @click="favorTopicDel">删除收藏</el-button>
      </div>
    </div>
    <!--thread.php 的请求完成后才显示-->
    <div id="content" style="min-height: 300px">
      <!--顶部操作区-->
      <forum-operations :data="data" :forum="forum" :hot-key="pageActions" :page-data="pageData" @refresh="refresh"/>
      <!--版头-->
      <!--主题列表-->
      <topic-table v-show="topics" :data="topics" :forum="forum" :selection="$route.name=== routeNames.thread.favor" @selection-change="selectionChanged"/>
      <!--底部操作区-->
      <forum-operations :data="data" :forum="forum" :hot-key="pageActions" :page-data="pageData" placement="bottom" @refresh="refresh"/>

      <!--权限信息弹窗-->
      <privilege-dialog/>
      <!--子版面弹窗-->
      <sub-forum-dialog v-if="forum && forum.hasOwnProperty('subForums')"/>
      <!--      版头弹窗-->
      <topped-topic-dialog/>
      <!--      被屏蔽主题弹窗-->
      <blocked-topics-dialog/>
      <!--热键提示-->
      <hotkey-dialog/>
    </div>
  </div>
</template>

<style scoped>

</style>